package com.cyb.binojcodesandbox.controller;

import com.cyb.binojcodesandbox.JavaDockerCodeSandbox;
import com.cyb.binojcodesandbox.JavaNativeCodeSandbox;
import com.cyb.binojcodesandbox.model.ExecuteCodeRequest;
import com.cyb.binojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class MainController {

    //定义鉴权请求头和请求参数
    public static final String AUTH_REQUEST_HEADER = "auth";

    public static final String AUTH_REQUEST_SECRET = "secretKey";

    @Resource
    private JavaNativeCodeSandbox JavaNativeCodeSandbox;

    @Resource
    private JavaDockerCodeSandbox JavadockerCodeSandbox;
    @GetMapping("/health")
    public String healthCheck(){
        return "ok";
    }

    /**
     * 执行代码
     *
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request,
                                    HttpServletResponse  response){
        //基本认证
        String header = request.getHeader(AUTH_REQUEST_HEADER);
        if(!AUTH_REQUEST_SECRET.equals(header)){
            response.setStatus(403);
            return null;
        }
        if(executeCodeRequest == null){
            throw new RuntimeException("请求参数为空");
        }
        return JavadockerCodeSandbox.executeCode(executeCodeRequest);
    }
}
